import plugin from '../../lib/plugins/plugin.js';
import { segment } from 'oicq';
import axios from 'axios';
import moment from 'moment';

//使用前请在云崽根目录输入 pnpm add -w axios

export class GenshinReRunPlugin extends plugin {
  constructor() {
    super({
      name: '原神复刻查询',
      dsc: '查询原神角色和武器的未复刻时间',
      event: 'message',
      priority: 100,
      rule: [
        {
          reg: '^#五星角色(未)?(复刻|计时器|复刻计时器)$',
          fnc: 'query5StarCharacters'
        },
        {
          reg: '^#四星角色(未)?(复刻|计时器|复刻计时器)$',
          fnc: 'query4StarCharacters'
        },
        {
          reg: '^#五星武器(未)?(复刻|计时器|复刻计时器)$',
          fnc: 'query5StarWeapons'
        },
        {
          reg: '^#四星武器(未)?(复刻|计时器|复刻计时器)$',
          fnc: 'query4StarWeapons'
        },
        {
          reg: '^#(四星|五星)?复刻$',
          fnc: 'txt'
        }
      ]
    });
  }

  async txt(e) {
        e.reply("查看原神卡池未复刻时间\n↓\n#五星角色未复刻\n#四星角色未复刻\n#五星武器未复刻\n#四星武器未复刻")
    }

  // 读取数据文件
  async fetchData() {
    try {
      const response = await axios.get('https://gitee.com/euiko/Panel/raw/img/gsKC.txt');
      return response.data;
    } catch (error) {
      console.error('获取数据失败:', error);
      return '';
    }
  }

  // 解析数据
  parseData(data) {
    const lines = data.split('\n');
    const entries = [];

    lines.forEach(line => {
      if (!line.trim()) return;
      
      const parts = line.split(' ');
      if (parts.length < 5) return;
      
      const version = parts[0];
      const date = parts[1];
      const fiveStarChars = parts[2].split(',');
      const fourStarChars = parts[3].split(',');
      const fiveStarWeapons = parts[4].split(',');
      const fourStarWeapons = parts[5]?.split(',');
      
      entries.push({
        version,
        date,
        fiveStarChars,
        fourStarChars,
        fiveStarWeapons,
        fourStarWeapons
      });
    });
    
    return entries;
  }

  // 计算未复刻天数（取最近一次出现的日期）
  calculateDaysAgo(dateString) {
  const targetDate = moment(dateString, 'YYYY-MM-DD');
  const now = moment();
  const diff = now.diff(targetDate);
  // 计算天数后取最大值，若为负数则设为0
  return Math.max(0, Math.floor(diff / (1000 * 60 * 60 * 24)));
}

  // 处理五星角色查询（取最近一次出现的版本）
  async query5StarCharacters(e) {
    const data = await this.fetchData();
    if (!data) {
      await this.reply('获取数据失败，请稍后再试。');
      return;
    }
    
    const entries = this.parseData(data);
    const charLastAppear = {}; // 记录角色最近一次出现的版本和日期

    // 遍历所有版本，更新角色最近出现的记录
    entries.forEach(entry => {
      entry.fiveStarChars.forEach(char => {
        // 若角色未记录或当前版本比已记录的版本更新，则更新记录
        if (!charLastAppear[char] || 
            moment(entry.date, 'YYYY-MM-DD').isAfter(moment(charLastAppear[char].date, 'YYYY-MM-DD'))) {
          charLastAppear[char] = {
            version: entry.version,
            date: entry.date
          };
        }
      });
    });
    
    // 转换为数组并按未复刻天数排序（天数多的在前）
    const resultArray = Object.entries(charLastAppear).map(([char, info]) => {
      const daysAgo = this.calculateDaysAgo(info.date);
      return { char, version: info.version, daysAgo };
    });
    
    resultArray.sort((a, b) => b.daysAgo - a.daysAgo);
    
    // 生成回复
    let reply = '五星角色-复刻计时器\n-\n';
    if (resultArray.length === 0) {
      reply += '暂无五星角色未复刻信息';
    } else {
      resultArray.forEach(item => {
        reply += `${item.version} ${item.char} ${item.daysAgo}天未复刻\n`;
      });
    }
    
    await this.reply(reply);
  }

  // 处理四星角色查询（逻辑同五星角色）
  async query4StarCharacters(e) {
    const data = await this.fetchData();
    if (!data) {
      await this.reply('获取数据失败，请稍后再试。');
      return;
    }
    
    const entries = this.parseData(data);
    const charLastAppear = {};

    entries.forEach(entry => {
      entry.fourStarChars.forEach(char => {
        if (!charLastAppear[char] || 
            moment(entry.date, 'YYYY-MM-DD').isAfter(moment(charLastAppear[char].date, 'YYYY-MM-DD'))) {
          charLastAppear[char] = {
            version: entry.version,
            date: entry.date
          };
        }
      });
    });
    
    const resultArray = Object.entries(charLastAppear).map(([char, info]) => {
      const daysAgo = this.calculateDaysAgo(info.date);
      return { char, version: info.version, daysAgo };
    });
    
    resultArray.sort((a, b) => b.daysAgo - a.daysAgo);
    
    let reply = '四星角色-复刻计时器\n-\n';
    if (resultArray.length === 0) {
      reply += '暂无四星角色未复刻信息';
    } else {
      resultArray.forEach(item => {
        reply += `${item.version} ${item.char} ${item.daysAgo}天未复刻\n`;
      });
    }
    
    await this.reply(reply);
  }

  // 处理五星武器查询（逻辑同五星角色）
  async query5StarWeapons(e) {
    const data = await this.fetchData();
    if (!data) {
      await this.reply('获取数据失败，请稍后再试。');
      return;
    }
    
    const entries = this.parseData(data);
    const weaponLastAppear = {};

    entries.forEach(entry => {
      entry.fiveStarWeapons.forEach(weapon => {
        if (!weaponLastAppear[weapon] || 
            moment(entry.date, 'YYYY-MM-DD').isAfter(moment(weaponLastAppear[weapon].date, 'YYYY-MM-DD'))) {
          weaponLastAppear[weapon] = {
            version: entry.version,
            date: entry.date
          };
        }
      });
    });
    
    const resultArray = Object.entries(weaponLastAppear).map(([weapon, info]) => {
      const daysAgo = this.calculateDaysAgo(info.date);
      return { weapon, version: info.version, daysAgo };
    });
    
    resultArray.sort((a, b) => b.daysAgo - a.daysAgo);
    
    let reply = '五星武器-复刻计时器\n-\n';
    if (resultArray.length === 0) {
      reply += '暂无五星武器未复刻信息';
    } else {
      resultArray.forEach(item => {
        reply += `${item.version} ${item.weapon} ${item.daysAgo}天未复刻\n`;
      });
    }
    
    await this.reply(reply);
  }

  // 处理四星武器查询（逻辑同五星角色）
  async query4StarWeapons(e) {
    const data = await this.fetchData();
    if (!data) {
      await this.reply('获取数据失败，请稍后再试。');
      return;
    }
    
    const entries = this.parseData(data);
    const weaponLastAppear = {};

    entries.forEach(entry => {
      if (entry.fourStarWeapons) {
        entry.fourStarWeapons.forEach(weapon => {
          if (!weaponLastAppear[weapon] || 
              moment(entry.date, 'YYYY-MM-DD').isAfter(moment(weaponLastAppear[weapon].date, 'YYYY-MM-DD'))) {
            weaponLastAppear[weapon] = {
              version: entry.version,
              date: entry.date
            };
          }
        });
      }
    });
    
    const resultArray = Object.entries(weaponLastAppear).map(([weapon, info]) => {
      const daysAgo = this.calculateDaysAgo(info.date);
      return { weapon, version: info.version, daysAgo };
    });
    
    resultArray.sort((a, b) => b.daysAgo - a.daysAgo);
    
    let reply = '四星武器-复刻计时器\n-\n';
    if (resultArray.length === 0) {
      reply += '暂无四星武器未复刻信息';
    } else {
      resultArray.forEach(item => {
        reply += `${item.version} ${item.weapon} ${item.daysAgo}天未复刻\n`;
      });
    }
    
    await this.reply(reply);
  }
}
